<template>
    <div style="display: flex;align-content: center;justify-content: center;height: 100%;" v-loading="loading">
        <div v-if="showNullBack">
            <h2>非法访问</h2>
        </div>
        <iframe v-if="showContainer && !showNullBack"
            sandbox="allow-forms allow-modals allow-popups   allow-same-origin allow-scripts allow-top-navigation allow-top-navigation"
            :src="externalUrl" width="100%" :height="iframe_height" frameborder="0" allowfullscreen @load="handleLoad">

        </iframe>
        <div v-if="!showContainer && !showNullBack">
            <h2> 考试结束！</h2>
        </div>
        <el-menu v-if="showContainer && !showNullBack" default-active="2" class="exp-right-menu" :collapse="true">
            <h3 style="writing-mode: vertical-rl; margin-top: 30px; margin-bottom: 30px;"> {{ title }}</h3>
            <el-countdown v-show="showCountDown" v-if="task_type === 'exam'" title="倒计时" :value="countDownValue"
                value-style="font-size: 15px; font-weight: bold;  margin-top: 20px; margin-bottom: 20px;" />

            <el-menu-item index="2" @click="handleBack">
                <el-icon>
                    <img src="@/assets/images/icon_back.png" width="20px" height="20px" alt="Icon" />
                </el-icon>
                <template #title>双击返回</template>
            </el-menu-item>

            <el-menu-item index="4" @click="handleBackupFiles">
                <el-icon>
                    <svg t="1716354545212" class="icon" viewBox="0 0 1195 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="7351" width="20" height="20">
                        <path
                            d="M606.994773 441.429333l149.333334 188.928a10.666667 10.666667 0 0 1-8.362667 17.237334H649.14944v323.072a10.666667 10.666667 0 0 1-10.666667 10.666666H558.52544a10.666667 10.666667 0 0 1-10.666667-10.666666V647.594667H449.298773a10.666667 10.666667 0 0 1-8.362666-17.237334l149.333333-188.928a10.666667 10.666667 0 0 1 16.725333 0zM598.888107 42.666667a426.837333 426.837333 0 0 1 398.933333 275.626666 266.666667 266.666667 0 0 1-68.352 524.373334h-53.504a10.666667 10.666667 0 0 1-10.666667-10.666667v-80.042667c0-5.802667 4.778667-10.581333 10.666667-10.581333h53.504c44.117333 0 85.589333-17.237333 116.736-48.469333 31.232-31.146667 48.469333-72.789333 48.469333-116.906667 0-74.922667-50.602667-140.629333-122.88-160.170667l-50.346666-13.312-18.432-48.64a327.68 327.68 0 0 0-117.504-151.04 322.816 322.816 0 0 0-186.624-58.965333c-67.328 0-131.84 20.394667-186.624 58.88a327.509333 327.509333 0 0 0-117.504 151.04l-18.517334 48.896-50.517333 13.141333c-34.730667 9.216-65.877333 29.866667-88.149333 58.282667a165.290667 165.290667 0 0 0 130.304 267.178667h53.418666c5.888 0 10.666667 4.864 10.666667 10.752v79.957333a10.666667 10.666667 0 0 1-10.666667 10.666667h-53.504a266.581333 266.581333 0 0 1-67.84-524.544A426.666667 426.666667 0 0 1 598.888107 42.666667z"
                            fill="#1296db" p-id="7352"></path>
                    </svg>
                </el-icon>
                <template #title>点击手动备份ipynb文件，上次备份时间：{{ last_backup_time }}</template>
            </el-menu-item>


            <el-sub-menu index="3">
                <template #title>
                    <el-icon>
                        <svg t="1716354154741" class="icon" viewBox="0 0 1248 1024" version="1.1"
                            xmlns="http://www.w3.org/2000/svg" p-id="2596" width="20" height="20">
                            <path
                                d="M889.555493 629.597406S780.028779 1009.372754 496.438364 841.514532c0 0-91.220549-44.058905-130.315071-181.510277l169.099318-135.279454L0 435.986444v515.054802l155.136989-135.279454A551.667132 551.667132 0 0 0 593.864393 1023.955631c288.554799-5.895206 316.479457-267.766442 295.6911-394.358225zM357.435622 393.478909S467.27261 13.393287 752.104121 181.561782c0 0 91.220549 43.748631 130.315071 181.510277L713.630148 498.041239l533.671241 89.048632V72.035068l-155.136989 134.96918A552.597954 552.597954 0 0 0 653.436996 0.051505c-288.554799 4.964384-316.479457 266.835621-296.001374 393.427404z"
                                fill="#1296db" p-id="2597"></path>
                        </svg>
                    </el-icon>
                </template>
                <el-sub-menu index="2" @click="handleGetBackupDirs">
                    <template #title>恢复ipynb文件</template>
                    <el-menu-item v-for="(item, index) in backup_dir_list" :key="index" :index="item.path"
                        @click="handleRecoverBackupFile(item.path)">
                        {{ item.name }}
                    </el-menu-item>
                </el-sub-menu>
            </el-sub-menu>
        </el-menu>

    </div>
</template>




<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount, onActivated } from 'vue'
import { useStore } from 'vuex'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
import { duplicate_student_files_api, getBackupDirAPI, RecoverBackupFileApi, getBackupSettingAPI, getExamStartTimeApi } from '@/api/clusterManagement'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { sendHeartbeat } from "@/utils/heartbeat";
import { watch } from 'vue'
const showContainer = ref(true)
const externalUrl = history.state.url
const title = history.state.title
const backup_interval_minutes = ref(15)
const backup_count = ref(5)
const handleLoad = () => {
    console.log('iframe loaded, loading: false');
    loading.value = false;
    if (task_type.value === 'exam') {
        ElMessageBox.prompt('点击开始考试后进入倒计时，本次考试时间为两小时，考试结束后自动关闭页面。输入“进入考试”开始考试。', '提示', {
            confirmButtonText: '确定',
            inputPattern: /^进入考试$/,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            closeOnHashChange: false,
            showClose: false,
            autofocus: false,
            showCancelButton: false,
            callback: (action: any) => {
                if (action.action === 'confirm') {
                    initCountDown()
                } else {
                    console.log('取消考试')
                    router.replace('/student/taskInfo')
                }
            }
        })
    }
}

const store = useStore()
const router = useRouter()
const countDownValue = ref(0)
const showCountDown = ref(false)
const loading = ref(true)
const task_type = ref(history.state.task_type)
const iframe_height = ref(900)
const handleBack = () => {
    // console.log('返回')
    // router.go(-1)
    ElMessageBox.confirm('确认返回吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            console.log('确认返回')
            router.replace('/student/taskInfo')
        }
        )
}
const last_backup_time = ref(null)
const backup_dir_list = ref([])
const duplicate_student_files = () => {
    // 向后端发送备份文件的指令
    console.log('开始备份文件, user_id:', store.state.user.user_id)
    duplicate_student_files_api(
        {
            course_id: history.state.course_id,
            task_id: history.state.task_id,
            user_id: store.state.user.user_id,
            task_type: history.state.task_type,
        }
    ).then((res: any) => {
        if (res.code === 200) {
            ElMessage.success('备份文件成功')
            last_backup_time.value = new Date().toLocaleString()
        }
    }).catch(err => {
        ElMessage.error('备份文件失败，请及时给老师反馈')
    })
}

const handleGetBackupDirs = () => {
    getBackupDirAPI({
        course_id: history.state.course_id,
        task_id: history.state.task_id,
        user_id: store.state.user.user_id,
        task_type: history.state.task_type,
    }).then((res: any) => {
        if (res.code === 200) {
            backup_dir_list.value = []
            for (let i = 0; i < res.data.length; i++) {
                backup_dir_list.value.push({
                    name: res.data[i].replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1-$2-$3 $4:$5:$6'),
                    path: res.data[i]
                })
                last_backup_time.value = res.data[i].replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1-$2-$3 $4:$5:$6');
            }
        } else {
            backup_dir_list.value = []
        }
    })
}

const handleBackupFiles = () => {
    ElMessageBox.confirm('备份当前文件', '提示', {})
        .then(() => {
            // 发送请求
            duplicate_student_files()
            console.log('确认备份文件')
        })
        .catch(() => {
            console.log('取消备份文件')
        }
        )
}
const handleRecoverBackupFile = (name: string) => {
    console.log('恢复备份文件', name)
    // 弹窗
    ElMessageBox.confirm('确认恢复备份文件吗？备份文件将覆盖现有文件。', '提示', {})
        .then(() => {
            // 发送请求
            console.log('确认恢复备份文件')
            RecoverBackupFileApi({
                backup_dir: name,
                course_id: history.state.course_id,
                task_id: history.state.task_id,
                user_id: store.state.user.user_id,
                task_type: history.state.task_type,
            }).then((res: any) => {
                if (res.code === 200) {
                    let file_list = res.data
                    ElMessage.success('恢复 ' + name + ' 成功，文件：' + file_list.join('，'))
                }
            })
        })
        .catch(() => {
            console.log('取消恢复备份文件')
        }
        )

}
const initCountDown = () => {
    if (task_type.value === 'exam') {
        getExamStartTimeApi({
            course_id: history.state.course_id,
            task_id: history.state.task_id,
            user_id: store.state.user.user_id,
        }).then((res: any) => {
            if (res.code === 200) {
                console.log('开始倒计时, countDownValue = ', res.data)
                countDownValue.value = res.data + Date.now()
                showCountDown.value = true;
                if (res.data === 0) {
                    loading.value = false;
                    showCountDown.value = false;
                    showContainer.value = false;
                }
            }
        })
    }
}
const notice_minutes = ref(15)
watch(countDownValue, (newVal) => {
    if (countDownValue.value === 1000 * 60 * notice_minutes.value) {
        ElNotification({
            title: '提示',
            message: `本次考试剩余${notice_minutes}分钟，请抓紧时间，确保最终代码保存成功。时间截止后将自动关闭该页面。`,
            duration: 0,
        })
    }
})
const getBackupSetting = () => {
    getBackupSettingAPI().then((res: any) => {
        if (res.code === 200) {
            backup_interval_minutes.value = res.data.backup_interval_minutes
            backup_count.value = res.data.backup_count
            intervalId = setInterval(duplicate_student_files, 1000 * 60 * backup_interval_minutes.value) // 每隔15分钟备份一次文件
        }
    })
}
const showNullBack = ref(false)
const judgeNullBack = () => {
    if (history.state.back === null || history.state.back === 'null')
        showNullBack.value = true;
}
let intervalId: any = null
onMounted(() => {
    judgeNullBack()
    getBackupSetting()
    handleGetBackupDirs()
    window.addEventListener('resize', adjustHeight)
    adjustHeight()
    setInterval(() => {
        sendHeartbeat(store.state.user.user_id, false)

    }, 1000 * 30);
})

const adjustHeight = () => {
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;
    iframe_height.value = screenHeight;
}
onBeforeUnmount(() => {
    clearInterval(intervalId);
    // 移除窗口大小改变事件监听
    window.removeEventListener('resize', adjustHeight);
});
onBeforeRouteLeave((to, from, next) => {
    duplicate_student_files()
    clearInterval(intervalId);

    next();
});
onActivated(() => {
    duplicate_student_files()
})
</script>

<style lang="scss" scoped>
.exp-right-menu {
    position: flex;
    top: 0;
    right: 0;
}
</style>